// 1.定义获取token方法
import { Base64 } from "js-base64";
function getToken(): string {
    const token = uni.getStorageSync("userInfo").user_Token || "";
    const base64_token = Base64.encode(token + ":");
    return "Basic " + base64_token;
}

const baseURL = 'https://meituan.thexxdd.cn/api/'; // 服务器地址

interface paramsType {
    url: string,
    method?: 'GET' | 'POST' | 'PUT' | 'DELETE',
    data?: {}
};

interface promiseType {
    data: any,
    msg: string
};

export default (params: paramsType): Promise<promiseType> => { // 3.定义返回数据类型
    let url = baseURL + params.url //   4.拼接url
    return new Promise((resolve, reject) => {
        uni.showLoading({
            title: '拼命加载中',
            mask: true
        })
        uni.request({
            url,
            method: params.method || 'GET',
            data: params.data,
            header: { Authorization: getToken() }, //`` 1.获取token
            success: res => {
                let { data, statusCode } = res
                switch (true) {
                    case statusCode === 200:
                        resolve(data as promiseType) // 2.返回数据
                        break;
                    case statusCode === 401:
                        uni.showToast({
                            title: '还没登录呢！',
                            icon: 'error'
                        })
                        setTimeout(() => {
                            uni.navigateTo({
                                url: '../login/login'
                            })
                        }, 1000);
                        reject(data)
                        break;
                    default:
                        reject(data)
                        break;
                }
                uni.hideLoading()
            },
            fail: res => {
                reject(res)
            }
        })
    })
};